import { IpcMainInvokeEvent } from 'electron';
import iconv from 'iconv-lite';
import XLSX from 'xlsx';
import path from 'path';
import fs from 'fs';
import { Task } from '../biz/ipc/feature.const';
import Log from './Log';
import CommonUtil from './common-util';
import { FileType } from '../const';
import ProgressUtil from './progress-util';

const TAG = 'PretreatUtil';

class PretreatUtil {
  private static instance: PretreatUtil;

  public static getInstance() {
    if (!this.instance) {
      this.instance = new PretreatUtil();
    }
    return this.instance;
  }

  public csvToExcel = async (
    event: IpcMainInvokeEvent,
    task: Task,
    scanDir: string,
    exportDir: string
  ) => {
    Log.i(TAG, 'start csvToExcel');
    const csvList = CommonUtil.getInstance().getAllFiles(scanDir, FileType.CSV);
    // CommonUtil.getInstance().rmDir(exportDir);
    Log.i(TAG, 'start convert:', csvList);
    for (let i = 0; i < csvList.length; i += 1) {
      const csvPath = csvList[i];
      Log.i(
        TAG,
        'r-----------------------start convert file----------------------'
      );
      const relativeFilePath = csvPath
        .replace(scanDir, '')
        .replace(FileType.CSV, FileType.XLSX);
      const outFilePath = path.join(exportDir, relativeFilePath);
      const baseDir = path.dirname(outFilePath);
      Log.i(TAG, 'outFilePath: ', outFilePath);
      Log.i(TAG, 'relativeFilePath: ', relativeFilePath);
      Log.i(TAG, 'start mkdir:', baseDir);
      CommonUtil.getInstance().mkdir(baseDir, () => {
        const csvBuffer = fs.readFileSync(csvPath);
        const csvData = iconv.decode(csvBuffer, 'gbk');
        const csv = XLSX.read(csvData, { type: 'string', raw: true });
        XLSX.writeFile(csv, outFilePath);
      });
      Log.i(
        TAG,
        'r--------------------------end convert--------------------------'
      );
      await CommonUtil.getInstance().sleep(200);
      ProgressUtil.getInstance().sendProgress({
        task,
        progress: (i + 1) / csvList.length,
      });
    }
  };
}

export default PretreatUtil;
